const { Section, Form, Project } = require('../models');

// 获取项目章节列表
const getSections = async (req, res) => {
  try {
    const { projectId } = req.params;
    const { page = 1, limit = 10, search, name } = req.query;

    // 验证项目是否存在
    const project = await Project.findById(projectId);
    if (!project) {
      return res.status(404).json({
        success: false,
        message: '项目未找到'
      });
    }

    const pageNum = parseInt(page, 10);
    const limitNum = parseInt(limit, 10);
    const startIndex = (pageNum - 1) * limitNum;
    const endIndex = pageNum * limitNum;

    // 获取所有配置的章节ID
    const allConfigSections = project.configSections || [];
    const total = allConfigSections.length;

    // 按顺序对整个数组进行排序
    const sortedConfigSections = allConfigSections.sort((a, b) => a.order - b.order);
      
    // 对排序后的数组进行分页
    const paginatedConfigSections = sortedConfigSections.slice(startIndex, endIndex);

    // 获取分页后章节的详细信息
    const sections = [];
    if (paginatedConfigSections.length > 0) {
      for (const sectionConfig of paginatedConfigSections) {
        const section = await Section.findById(sectionConfig.sectionId)
          .populate({
            path: 'forms',
            options: { sort: { order: 1 } }
          });
        
        if (section) {
          // 名称关键字过滤（后过滤，避免破坏分页逻辑过多；若需更准确可先过滤再分页）
          const keyword = (search || name || '').trim();
          if (keyword && !new RegExp(keyword, 'i').test(section.name)) {
            continue;
          }
          sections.push({
            ...section.toObject(),
            order: sectionConfig.order,
            config: {
              ...section.config,
              ...sectionConfig.config
            }
          });
        }
      }
    }

    res.json({
      success: true,
      data: sections,
      pagination: {
        total,
        page: pageNum,
        limit: limitNum,
        pages: Math.ceil(total / limitNum)
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取章节列表失败',
      error: error.message
    });
  }
};

// 获取所有模板章节
const getAllTemplateSections = async (req, res) => {
  try {
    const sections = await Section.find({ isTemplate: true })
      .sort({ name: 1 })
      .populate({
        path: 'forms',
        options: { sort: { order: 1 } }
      });

    res.json({
      success: true,
      data: sections
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取模板章节列表失败',
      error: error.message
    });
  }
};

// 获取章节详情
const getSection = async (req, res) => {
  try {
    const { id } = req.params;

    const section = await Section.findById(id)
      .populate({
        path: 'forms',
        options: { sort: { order: 1 } }
      });

    if (!section) {
      return res.status(404).json({
        success: false,
        message: '章节未找到'
      });
    }

    res.json({
      success: true,
      data: section
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取章节详情失败',
      error: error.message
    });
  }
};

// 创建章节
const createSection = async (req, res) => {
  try {
    const { projectId } = req.params;
    
    // 验证项目是否存在
    const project = await Project.findById(projectId);
    if (!project) {
      return res.status(404).json({
        success: false,
        message: '项目未找到'
      });
    }

    // 如果没有指定顺序，设置为最后一个
    if (!req.body.order) {
      const existingSections = project.configSections || [];
      const maxOrder = existingSections.length > 0 
        ? Math.max(...existingSections.map(s => s.order))
        : 0;
      req.body.order = maxOrder + 1;
    }

    // 创建章节（不包含projectId，因为Section模型中没有这个字段）
    const sectionData = {
      ...req.body
    };

    const section = new Section(sectionData);
    await section.save();

    // 更新项目的configSections数组，添加新章节
    await Project.findByIdAndUpdate(
      projectId,
      { 
        $push: { 
          configSections: {
            sectionId: section._id,
            order: req.body.order,
            config: req.body.config || {}
          }
        } 
      }
    );

    // 返回包含项目关联信息的章节数据
    const sectionWithProject = {
      ...section.toObject(),
      projectId: projectId,
      order: req.body.order
    };

    res.status(201).json({
      success: true,
      message: '章节创建成功',
      data: sectionWithProject
    });
  } catch (error) {
    console.error('创建章节失败:', error);
    res.status(500).json({
      success: false,
      message: '创建章节失败',
      error: error.message
    });
  }
};

// 更新章节
const updateSection = async (req, res) => {
  try {
    const { id } = req.params;

    console.log('更新章节请求:', {
      id,
      body: req.body
    });

    // 先获取原章节信息（用于比较forms变化）
    const originalSection = await Section.findById(id);
    if (!originalSection) {
      return res.status(404).json({
        success: false,
        message: '章节未找到'
      });
    }

    // 处理forms字段的更新（如果存在）
    if (req.body.forms && Array.isArray(req.body.forms)) {
      const originalFormIds = originalSection.forms || [];
      const newFormIds = req.body.forms;

      // 找出新增的表单
      const addedFormIds = newFormIds.filter(formId => 
        !originalFormIds.some(originalId => originalId.toString() === formId.toString())
      );

      // 找出移除的表单
      const removedFormIds = originalFormIds.filter(originalId => 
        !newFormIds.some(newId => newId.toString() === originalId.toString())
      );

      console.log('表单关联变化:', {
        原始表单: originalFormIds.map(id => id.toString()),
        新表单: newFormIds.map(id => id.toString()),
        新增: addedFormIds.map(id => id.toString()),
        移除: removedFormIds.map(id => id.toString())
      });

      // 更新新增表单的sectionId（移除projectId，因为Form模型中没有这个字段）
      if (addedFormIds.length > 0) {
        await Form.updateMany(
          { _id: { $in: addedFormIds } },
          { $set: { sectionId: id } }
        );
        console.log('已更新新增表单的sectionId:', addedFormIds.map(id => id.toString()));
      }

      // 清除移除表单的sectionId
      if (removedFormIds.length > 0) {
        await Form.updateMany(
          { _id: { $in: removedFormIds } },
          { $unset: { sectionId: "" } }
        );
        console.log('已清除移除表单的sectionId:', removedFormIds.map(id => id.toString()));
      }
    }

    // 更新章节信息
    const section = await Section.findByIdAndUpdate(
      id,
      req.body,
      { new: true, runValidators: true }
    ).populate({
      path: 'forms',
      options: { sort: { order: 1 } }
    });

    // 如果更新了order字段，同时更新项目的configSections中的order
    if (req.body.order !== undefined) {
      const project = await Project.findOne({ 
        'configSections.sectionId': id 
      });
      
      if (project) {
        await Project.updateOne(
          { 
            '_id': project._id,
            'configSections.sectionId': id 
          },
          { 
            $set: { 
              'configSections.$.order': req.body.order 
            } 
          }
        );
        console.log('已更新项目配置中的章节顺序:', req.body.order);
      }
    }

    console.log('更新后的章节:', {
      id: section._id,
      name: section.name,
      order: req.body.order || section.order,
      formsCount: section.forms?.length || 0,
      forms: section.forms?.map(f => ({ id: f._id, name: f.name })) || []
    });

    // 返回包含正确order字段的章节数据
    const responseData = {
      ...section.toObject(),
      order: req.body.order !== undefined ? req.body.order : section.order
    };

    res.json({
      success: true,
      message: '章节更新成功',
      data: responseData
    });
  } catch (error) {
    console.error('更新章节失败:', error);
    res.status(500).json({
      success: false,
      message: '更新章节失败',
      error: error.message
    });
  }
};

// 删除章节
const deleteSection = async (req, res) => {
  try {
    const { id } = req.params;

    const section = await Section.findById(id).populate('forms');
    if (!section) {
      return res.status(404).json({
        success: false,
        message: '章节未找到'
      });
    }

    // 检查是否有关联的表单
    if (section.forms && section.forms.length > 0) {
      return res.status(400).json({
        success: false,
        message: '该章节下还有关联表单，请先删除所有表单后再删除章节',
        data: {
          formCount: section.forms.length,
          forms: section.forms.map(form => ({
            id: form._id,
            name: form.name,
            code: form.code
          }))
        }
      });
    }

    // 从所有项目的configSections数组中移除该章节
    await Project.updateMany(
      { 'configSections.sectionId': id },
      { $pull: { configSections: { sectionId: id } } }
    );

    // 删除章节
    await Section.findByIdAndDelete(id);

    res.json({
      success: true,
      message: '章节删除成功'
    });
  } catch (error) {
    console.error('删除章节失败:', error);
    res.status(500).json({
      success: false,
      message: '删除章节失败',
      error: error.message
    });
  }
};

// 重新排序章节
const reorderSections = async (req, res) => {
  try {
    const { projectId } = req.params;
    const { sections } = req.body;

    // 验证项目是否存在
    const project = await Project.findById(projectId);
    if (!project) {
      return res.status(404).json({
        success: false,
        message: '项目未找到'
      });
    }

    // 更新项目中的configSections顺序
    const updatedConfigSections = sections.map(({ id, order }) => ({
      sectionId: id,
      order: order,
      config: {} // 保持原有配置或使用默认配置
    }));

    await Project.findByIdAndUpdate(
      projectId,
      { $set: { configSections: updatedConfigSections } }
    );

    // 重新获取排序后的章节列表
    const updatedSections = [];
    for (const sectionConfig of updatedConfigSections) {
      const section = await Section.findById(sectionConfig.sectionId)
        .populate({
          path: 'forms',
          options: { sort: { order: 1 } }
        });
      
      if (section) {
        updatedSections.push({
          ...section.toObject(),
          order: sectionConfig.order,
          config: {
            ...section.config,
            ...sectionConfig.config
          }
        });
      }
    }

    res.json({
      success: true,
      message: '章节排序更新成功',
      data: updatedSections
    });
  } catch (error) {
    console.error('更新章节排序失败:', error);
    res.status(500).json({
      success: false,
      message: '更新章节排序失败',
      error: error.message
    });
  }
};

module.exports = {
  getSections,
  getAllTemplateSections,
  getSection,
  createSection,
  updateSection,
  deleteSection,
  reorderSections
};